Node.js — module.exports vs exports, what’s the difference ?
1922 단어 nodeJS
// -- hello.js
exports.anything = function() {
console.log('I am anything.');
};
// -- hello-runner.js
const hello = require('./hello');
// let's see what's there in hello variable
console.log(hello); // {anything: Function}
hello.anything(); // I am anything.
Similar use of module.exports
// -- hello.js
module.exports.anything = function() {
console.log('I am anything.');
};
// -- hello-runner.js
const hello = require('./hello');
// let's see what's there in hello variable
console.log(hello); // {anything: Function}
hello.anything(); // I am anything.
Similar output.
So, what the difference ?
Exports is just module.exports's little helper. Your module returns module.exports to the caller ultimately, not exports. All exports does is collect properties and attach them to module.exports
BUT...
IF module.exports doesn't have something on it already. If there's something attached to module.exports already, everything on exports is ignored.
// -- hello.js
module.exports = {
hi: function() {
console.log('hi');
},
};
// ALERT - this won't be exported.
exports.bye = function() {
console.log('bye');
};
What if we assign a value to module.exports or exports ?
// hello.js file
module.exports = {a: 1}
// hello-runner.js
const hello = require('./hello');
console.log(hello); // {a: 1}
This works. but, direct assignment to exports variable doesn't work.
// hello.js file
exports = {a: 1}
// hello-runner.js
const hello = require('./hello');
console.log(hello); // { }
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Node.js — module.exports vs exports, what’s the difference ?Simple use of exports, Similar use of module.exports Similar output. So, what the difference ? Exports is just module.ex...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.